
$(document).ready(function(){
    // render
    //loadData();
    // event
    _listBillCurrent = null;
    _listBillDelete = null;
    bindEvent();
});

function loadData() {
    ISS.CONTROL.lockScreen('#content');
    ISS.BACKEND.request({
        url: SERVER.contextPath + '/service/admin/getBillCommon',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        type: 'GET',
        dataType: 'json',
        success: function (data) {
            var responseContent = data.responseObject;
            mapBillToViewHandelBar(responseContent);
            ISS.CONTROL.unLockScreen();
        }
    });

    ISS.BACKEND.request({
        url: SERVER.contextPath + '/service/admin/getBillDetailCommon',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        type: 'POST',
        dataType: 'json',
        success: function (data) {
            var responseContent = data.responseObject;
            mapBillDetailToView(responseContent);
        }
    });

    ISS.BACKEND.request({
        url: SERVER.contextPath + '/service/admin/getAllMemberBill',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        type: 'GET',
        dataType: 'json',
        success: function (data) {
            var responseContent = data.responseObject;
            mapMemberBillToView(responseContent);
        }
    });

    ISS.BACKEND.request({
        url: SERVER.contextPath + '/service/admin/getAllBillCode',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        type: 'GET',
        dataType: 'json',
        success: function (data) {
            var responseContent = data.responseObject;
            mapBillCodeToView(responseContent);
        }
    });

    ISS.BACKEND.request({
        url: SERVER.contextPath + '/service/admin/getAllProductDetailCodeInBill',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        type: 'GET',
        dataType: 'json',
        success: function (data) {
            var responseContent = data.responseObject;
            mapProductDetailCodeToView(responseContent);
        }
    });

    //    Get date current
    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth()+1; //January is 0!
    var yyyy = today.getFullYear();

    if(dd<10) {
        dd='0'+dd
    }

    if(mm<10) {
        mm='0'+mm
    }

    today = dd+'-'+mm+'-'+yyyy;
    ISS.DOM.setVal('#BillCommon_DateCreate', today);
    ISS.DOM.setVal('#BillCommon_DateBegin', today);

//    var today = today.split("-");
//    var newdateCreate = today[2]+'-'+today[1]+'-'+today[0];
//    var newdateCreate = ISS.DATE.changeFormatDate(ISS.DOM.getVal('#BillCommon_DateCreate'));
//    ISS.DOM.setVal('#BillCommon_DateEnd', newdateCreate);

}

function bindEvent() {
    ISS.EVENT.bindEvent('#BillCommon_Add1', 'click', function () {
        clearValidateInfo_Add();
        if(validateInfo_Add()){
            sendInfo();
        }
        else {
            $('#message-error-admin div').empty();
            var htmlText = '<div class="message-error-admin">\
                                Thêm hóa đơn mới thất bại\
                            </div>';
            ISS.DOM.html('.show-message-error', htmlText);

            var htmlText = '<div class="show-message-error-admin align-center">\
                                <img src="../../images/table/error.png" width="40" height="40" /> \
                                Xin hoàn tất những ô được bôi đỏ\
                            </div>';
            ISS.DOM.html('.show-message-error-admin', htmlText);
        }
    });

    ISS.EVENT.bindEvent('#BillCommon_Modified', 'click', function () {
        toEditPage();
    });

    ISS.EVENT.bindEvent('#BillCommon_UpdateStatus', 'click', function () {
        toGetData();
    });

    ISS.EVENT.bindEvent('#sorted-arrange-button', 'click', function () {
        toGetDataSort();
    });

    ISS.EVENT.bindEvent('#search_button', 'click', function () {
        toGetDataSearch();
        ISS.DOM.removeClass('#boxBillCommon', 'hideBox');
    });

    ISS.EVENT.bindEvent('#BillDetailCommon_Delete', 'click', function () {
        deleteBillDetail();
    });

    ISS.EVENT.bindEvent('#buttonUpdateStatusBill_Cancel', 'click', function () {
        hideBoxConfirm();
    });

    ISS.EVENT.bindEvent('#buttonUpdateStatusBill_Agree', 'click', function () {
        updateFinishBillCommon();
        ISS.DOM.addClass('#boxTrackConfirm', 'hideBox');
    });
}

function updateFinishBillCommon() {
    var _maHD = [];
    var bill = {};

    bill.thanhToan = ISS.DOM.getVal('#BillCommon_StatusID');
    if(bill.thanhToan == 0){
        bill.trangThai = 0;
    }else{
        bill.trangThai = 1;
    }

    ISS.DOM.forEach('#form-BillCommon input[type="checkbox"]:checked', function(){
        _maHD.push($(this).val());
    });

    bill.maHD = _maHD[0];

    if(_maHD.length == 1) {
        ISS.BACKEND.request({
            url: SERVER.contextPath + '/service/admin/header/updateStatusBillCommon',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            type: 'POST',
            dataType: 'json',
            data: JSON.stringify(bill),
            success: function (data) {
                var responseContent = data.responseObject;
//                mapBillToView(responseContent);
//                reLoadData();
                var _url = '/jsp/admin/ad-bill-common.jsp';
                ISS.WINDOW.location(_url);
            }
        });
    }
    else {
        alert('Bạn chưa chọn hoặc đã chọn hơn 1 dòng');
    }
}

function deleteBillDetail() {
    var billDetail = {};
    var listBillDetail = [];
    var lstHoaDon=[];

    ISS.DOM.forEach('#form-AdBillDetailCommon input[type="checkbox"]:checked', function(){
        listBillDetail.push($(this).val());
    });
    if(listBillDetail.length > 0) {
        for(var i =0; i < listBillDetail.length; i++) {
            billDetail.maHD = listBillDetail[i];
            lstHoaDon.push(billDetail);
        }

        ISS.BACKEND.request({
            url: SERVER.contextPath + '/service/admin/deleteBillDetail',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            type: 'POST',
            dataType: 'json',
            data: JSON.stringify(lstHoaDon),
            success: function (data) {
                var responseContent = data.responseObject;
                mapBillToViewHandelBarAgian(responseContent);
            }
        });

    }
    else {
        alert('Bạn chưa chọn');
    }

}

function sendInfo() {
    var bill = {};
    var member = {};

    bill.maHD = ISS.DOM.getVal('#BillCommon_Code');
    bill.hoTenNN = ISS.DOM.getVal('#BillCommon_Receiver');
    bill.soDTNN = ISS.DOM.getVal('#BillCommon_ReceiverPhone');
    bill.diaChiNN = ISS.DOM.getVal('#BillCommon_ReceiverAddress');
    bill.ngayLapHD = ISS.DATE.changeFormatDate(ISS.DOM.getVal('#BillCommon_DateCreate'));
    bill.ngayDat = ISS.DATE.changeFormatDate(ISS.DOM.getVal('#BillCommon_DateBegin'));
    bill.ngayGiao = ISS.DATE.changeFormatDate(ISS.DOM.getVal('#BillCommon_DateEnd'));
    bill.trangThai = ISS.DOM.getVal('#BillCommon_Status');
    bill.thanhToan = ISS.DOM.getVal('#BillCommon_Finish');
    bill.ghiChu = ISS.DOM.getVal('#BillCommon_Note');
    bill.tongTien = ISS.DOM.getVal('#BillCommon_Total');
    member.maTV  = ISS.DOM.getVal('#BillCommon_Member');
    bill.thongTinThanhVien = member;

    ISS.BACKEND.request({
        url: SERVER.contextPath + '/service/admin/header/adBillCommon',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify(bill),
        success: function (data) {
            var responseContent = data.responseObject;
        }
    });
}

function toEditPage() {
    var _maHD = [];
    ISS.DOM.forEach('#form-BillCommon input[type="checkbox"]:checked', function(){
        _maHD.push($(this).val());
    });

    if(_maHD.length == 1) {
        var _url = '/service/admin/toBillPage/' + _maHD[0];
        ISS.WINDOW.location(_url);
    }
    else {
        alert('Bạn chưa chọn hoặc đã chọn hơn 1 dòng');
    }
}

function toGetData() {
    var _maHD = [];
    ISS.DOM.forEach('#form-BillCommon input[type="checkbox"]:checked', function(){
        _maHD.push($(this).val());
    });

    if(_maHD.length == 1) {

        _maHD = _maHD[0];

        var bill = {};
        bill.maHD = _maHD;

        ISS.BACKEND.request({
            url: SERVER.contextPath + '/service/admin/bill_toGetData',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            type: 'POST',
            dataType: 'json',
            data: JSON.stringify(bill),
            success: function (data) {
                var responseContent = data.responseObject;
                loadDataComplete(responseContent);
            }
        });

        ISS.DOM.removeClass('#boxTrackConfirm', 'hideBox');

    } else {
        alert('Bạn chưa chọn hoặc đã chọn hơn 1 dòng');
    }

}

function toGetDataSort() {
    var name, updown;
    name = ISS.DOM.getVal('#form-sorted-name');
    updown = ISS.DOM.getVal('#form-sorted-up-down');

    if(name == "non_value" || updown =="non_value") {
        alert('Mời bạn chọn đầy đủ thông tin trong trường sắp xếp');
    } else {
        if(name == 0){
            name = "thongTinThanhVien.ten";
        } else if (name == 1) {
            name = "hoTenNN";
        } else if (name == 2) {
            name = "ngayLapHD";
        } else if (name == 3) {
            name = "ngayDat";
        } else if (name == 4) {
            name = "ngayGiao";
        } else if (name == 5) {
            name = "thanhToan";
        } else {
            name = "tongTien";
        }
        ISS.CONTROL.lockScreen('#content');
        ISS.BACKEND.request({
            url: SERVER.contextPath + '/service/admin/header/getDataSortInBill/' + name + '/' + updown,
            type: 'GET',
            success: function (data) {
                var responseInfo = data.responseObject;
                mapBillToViewHandelBar(responseInfo);
                ISS.CONTROL.unLockScreen()
            }
        });
    }

}

function toGetDataSearch() {
    var name, content;
    name = ISS.DOM.getVal('#form-deal-common-compare-name');
    content = ISS.DOM.getVal('#input_name_search');

    var dateBegin, dateEnd;
    dateBegin = ISS.DOM.getVal('#input_name_search_time_begin');
    dateEnd = ISS.DOM.getVal('#input_name_search_time_end');

    var finish, status;
    finish = ISS.DOM.getVal('#form-bill-common-finish');
    status = ISS.DOM.getVal('#form-bill-common-status');

    var time;
    time = ISS.DOM.getVal('#form-deal-common-compare-time');

    if(name == "non_value") {
        alert('Mời bạn chọn danh mục cần tìm kiếm');
        ISS.DOM.addClass('#boxBillCommon', 'hideBox');
    }
    else {
        if (name == 0 || name == 1 || name == 2 || name == 3){
            if(content != ""){
                if(name == 0){
                    name = "thongTinThanhVien.ten";
                } else if (name == 1) {
                    name = "hoTenNN";
                } else if (name == 2) {
                    name = "diaChiNN";
                } else if (name == 3) {
                    name = "soDTNN";
                }
                ISS.CONTROL.lockScreen('#content');
                ISS.BACKEND.request({
                    url: SERVER.contextPath + '/service/admin/header/getDataSearchInBill?name=' + name + '&content=' + content,
                    type: 'GET',
                    success: function (data) {
                        var responseInfo = data.responseObject;
                        mapBillToViewHandelBar(responseInfo);
                        ISS.CONTROL.unLockScreen();
                    }
                });

            } else {
                alert('Mời bạn nhập thông tin cần tìm kiếm');
                ISS.DOM.addClass('#boxBillCommon', 'hideBox');
            }
        }

        else if (name == 4 || name == 5 || name == 6){
            if ( dateBegin != "" && dateEnd != ""){
                if(name == 4){
                    name = "ngayLapHD";
                } else if (name == 5) {
                    name = "ngayNhan";
                } else if (name == 6) {
                    name = "ngayGiao";
                }
                ISS.CONTROL.lockScreen('#content');
                ISS.BACKEND.request({
                    url: SERVER.contextPath + '/service/admin/header/getDateSearchInBill/' + name + '/' + dateBegin + '/' + dateEnd,
                    type: 'GET',
                    success: function (data) {
                        var responseInfo = data.responseObject;
                        if(responseInfo.length != 0) {
                            $('#boxBillSearch_None div').empty();
                            mapBillToViewHandelBar(responseInfo);
                            ISS.CONTROL.unLockScreen();
                        }
                        else {
//                            alert('Không có dữ liệu');
                            $('#boxBillSearch_None div').empty();
                            var htmlText = '<div class="BillSearch_None align-center">\
                                Không có dữ liệu phù hợp\
                            </div>';
                            ISS.DOM.html('.BillSearch_None', htmlText);

                            ISS.CONTROL.unLockScreen();
                            ISS.DOM.addClass('#boxBillCommon', 'hideBox');
                        }
                    }
                });

            } else {
                alert('Mời bạn chọn cả ngày bắt đầu và kết thúc');
                ISS.DOM.addClass('#boxBillCommon', 'hideBox');
            }
        }

        else if (name == 7){
            if(finish != "non_value" & time!= "non_value"){
                if(time == 0){
                    time = "ngayLapHD";
                } else if (time == 1) {
                    time = "ngayDat";
                } else if (time == 2) {
                    time = "ngayGiao";
                }
                name = "thanhToan";
                ISS.CONTROL.lockScreen('#content');
                ISS.BACKEND.request({
                    url: SERVER.contextPath + '/service/admin/header/getFinishTimeSearchInBill/' + name + '/' + finish + '/' + time + '/' + dateBegin + '/' + dateEnd,
                    type: 'GET',
                    success: function (data) {
                        var responseInfo = data.responseObject;
                        mapBillToViewHandelBar(responseInfo);
                        ISS.CONTROL.unLockScreen();
                    }
                });
            } else if (finish != "non_value" & time== "non_value") {
                name = "thanhToan";
                ISS.CONTROL.lockScreen('#content');
                ISS.BACKEND.request({
                    url: SERVER.contextPath + '/service/admin/header/getFinishSearchInBill/' + name + '/' + finish,
                    type: 'GET',
                    success: function (data) {
                        var responseInfo = data.responseObject;
                        mapBillToViewHandelBar(responseInfo);
                        ISS.CONTROL.unLockScreen();
                    }
                });
            } else {
                alert('Mời bạn chọn mục cần tìm kiếm');
                ISS.DOM.addClass('#boxBillCommon', 'hideBox');
            }
        }

        else if (name == 8){
            if(status != "non_value" & time!= "non_value"){
                if(time == 0){
                    time = "ngayLapHD";
                } else if (time == 1) {
                    time = "ngayDat";
                } else if (time == 2) {
                    time = "ngayGiao";
                }
                name = "thanhToan";
                ISS.CONTROL.lockScreen('#content');
                ISS.BACKEND.request({
                    url: SERVER.contextPath + '/service/admin/header/getStatusTimeSearchInBill/' + name + '/' + status + '/' + time + '/' + dateBegin + '/' + dateEnd,
                    type: 'GET',
                    success: function (data) {
                        var responseInfo = data.responseObject;
                        mapBillToViewHandelBar(responseInfo);
                        ISS.CONTROL.unLockScreen();
                    }
                });
            } else if(status != "non_value" & time== "non_value"){
                name = "trangThai";
                ISS.CONTROL.lockScreen('#content');
                ISS.BACKEND.request({
                    url: SERVER.contextPath + '/service/admin/header/getStatusSearchInBill/' + name + '/' + status,
                    type: 'GET',
                    success: function (data) {
                        var responseInfo = data.responseObject;
                        mapBillToViewHandelBar(responseInfo);
                        ISS.CONTROL.unLockScreen();
                    }
                });
            } else {
                alert('Mời bạn chọn mục cần tìm kiếm');
                ISS.DOM.addClass('#boxBillCommon', 'hideBox');
            }
        }

        else if (name == 9){
            if(finish != "non_value" && status != "non_value" & time!= "non_value"){
                if(time == 0){
                    time = "ngayLapHD";
                } else if (time == 1) {
                    time = "ngayDat";
                } else if (time == 2) {
                    time = "ngayGiao";
                }
                ISS.CONTROL.lockScreen('#content');
                ISS.BACKEND.request({
                    url: SERVER.contextPath + '/service/admin/header/getFinish_StatusTimeSearchInBill/' + finish + '/' + status + '/' + time + '/' + dateBegin + '/' + dateEnd,
                    type: 'GET',
                    success: function (data) {
                        var responseInfo = data.responseObject;
                        mapBillToViewHandelBar(responseInfo);
                        ISS.CONTROL.unLockScreen();
                    }
                });
            } else if(finish != "non_value" && status != "non_value" & time== "non_value"){
                ISS.CONTROL.lockScreen('#content');
                ISS.BACKEND.request({
                    url: SERVER.contextPath + '/service/admin/header/getFinish_StatusSearchInBill/' + finish + '/' + status,
                    type: 'GET',
                    success: function (data) {
                        var responseInfo = data.responseObject;
                        mapBillToViewHandelBar(responseInfo);
                        ISS.CONTROL.unLockScreen();
                    }
                });
            } else {
                alert('Mời bạn chọn đầy đủ các mục');
                ISS.DOM.addClass('#boxBillCommon', 'hideBox');
            }
        }

    }
}

///

function loadDataComplete(bill){
    ISS.DOM.setVal('#BillCommon_StatusID', bill.thanhToan);

    var finish = ISS.DOM.getVal('#BillCommon_StatusID');
    if (finish == 1){
        ISS.DOM.setVal('#BillCommon_StatusID', 0); //Chuyen tu hoan tat sang chua hoan tat
    }
    else{
        ISS.DOM.setVal('#BillCommon_StatusID', 1); //Chuyen tu chua hoan tat sang hoan tat
    }
}

function validateInfo_Add() {
//    all variable bill
    var code, member, dateCreate, dateBegin, dateEnd, status, finish, total, result;
//    all variable receiver
    var receiver, receiverAddress, receiverPhone;

    code = ISS.DOM.getVal('#BillCommon_Code');
    member = ISS.DOM.getVal('#BillCommon_Member');
    dateCreate = ISS.DOM.getVal('#BillCommon_DateCreate');
    dateBegin = ISS.DOM.getVal('#BillCommon_DateBegin');
    dateEnd = ISS.DOM.getVal('#BillCommon_DateEnd');
    status = ISS.DOM.getVal('#BillCommon_Status');
    finish = ISS.DOM.getVal('#BillCommon_Finish');
    total = ISS.DOM.getVal('#BillCommon_Total');
    receiver = ISS.DOM.getVal('#BillCommon_Receiver');
    receiverAddress = ISS.DOM.getVal('#BillCommon_ReceiverAddress');
    receiverPhone = ISS.DOM.getVal('#BillCommon_ReceiverPhone');

    if(!code) {
        ISS.DOM.addClass('#BillCommon_Code', 'error-input-not-null');
        result = false;
    }

    if(member == "non_value") {
        ISS.DOM.addClass('#BillCommon_Member', 'error-input-not-null');
        result = false;
    }

    if(!receiver) {
        ISS.DOM.addClass('#BillCommon_Receiver', 'error-input-not-null');
        result = false;
    }

    if(!receiverAddress) {
        ISS.DOM.addClass('#BillCommon_ReceiverAddress', 'error-input-not-null');
        result = false;
    }

    if(!receiverPhone) {
        ISS.DOM.addClass('#BillCommon_ReceiverPhone', 'error-input-not-null');
        result = false;
    }

    if(!dateCreate) {
        ISS.DOM.addClass('#BillCommon_DateCreate', 'error-input-not-null');
        result = false;
    }

    if(!dateBegin) {
        ISS.DOM.addClass('#BillCommon_DateBegin', 'error-input-not-null');
        result = false;
    }

    if(!dateEnd) {
        ISS.DOM.addClass('#BillCommon_DateEnd', 'error-input-not-null');
        result = false;
    }

    if(status == "non_value") {
        ISS.DOM.addClass('#BillCommon_Status', 'error-input-not-null');
        result = false;
    }

    if(finish == "non_value") {
        ISS.DOM.addClass('#BillCommon_Finish', 'error-input-not-null');
        result = false;
    }

    if(!total) {
        ISS.DOM.addClass('#BillCommon_Total', 'error-input-not-null');
        result = false;
    }

    return result;
}

function mapBillToViewHandelBar(bill) {
    _listBillCurrent = bill;
    var str = '';
    generaDataBill(bill);
    for(var i = 0; i < bill.length; i++) {
        var tem = ISS.STRING_UTIL.format(ISS.TEMPLATE.handleBar.renderByString(TEMPLATE.BillCommon.billTableRow, bill[i]), {
            optionStatus: bill[i].optionStatus,
            optionPayment: bill[i].optionPayment
        });
        str += tem;
        delete bill[i].optionStatus;
        delete bill[i].optionPayment;
        delete bill[i].showStatus;
        delete bill[i].showPayment;
        delete bill[i].showTick;
    }
    var table = ISS.STRING_UTIL.format(TEMPLATE.BillCommon.billTable, {
        listBill: str
    });
    ISS.DOM.html('#BillCommon_All', table);
    ISS.DOM.pagingAdmin('#form_BillCommon');

    // event
    bindEventTableBill(bill);
}

function mapBillToViewHandelBarAgian(bill) {
    _listBillCurrent = bill;
   var str = '';
    generaDataBillAgain(bill);
    for(var i = 0; i < bill.length; i++) {
        var tem = ISS.STRING_UTIL.format(ISS.TEMPLATE.handleBar.renderByString(TEMPLATE.BillCommon.billTableRow, bill[i]), {
            optionStatus: bill[i].optionStatus,
            optionPayment: bill[i].optionPayment
        });
        str += tem;
        delete bill[i].optionStatus;
        delete bill[i].optionPayment;
        delete bill[i].showStatus;
        delete bill[i].showPayment;
        delete bill[i].showTick;
    }
    var table = ISS.STRING_UTIL.format(TEMPLATE.BillCommon.billTable, {
        listBill: str
    });
    ISS.DOM.html('#BillCommon_All', table);
    ISS.DOM.pagingAdmin('#form_BillCommon');

    // event
    bindEventTableBill(bill);
}

function bindEventTableBill(bill) {
    for(var i = 0; i < bill.length; i++) {
        ISS.EVENT.bindEvent('#columnBill_status_' + bill[i].maHD, 'change', function () {
            var r = confirm("Bạn có muốn cập nhật ?");
            if (r == true) {
                var _status = ISS.DOM.getVal('#'+this.id);
                var _id = ISS.DOM.getData('#' + this.id, 'id');

                ISS.BACKEND.request({
                    url: SERVER.contextPath + '/service/admin/updateStatusBill/' + _id + '/' + _status,
                    type: 'POST',
                    success: function (data) {
                        var responseInfo = data.responseObject;
                        if(responseInfo) {
                            var bill = [responseInfo];
                            updateCurrentlist(bill);
                            mapBillUpdateToViewHandelBar(bill);
                            alert('Cập nhật thành công !');
                        }
                        else {
                            alert('Cập nhật không hợp lệ !');
                        }
                    }
                });
            }
            else {
                mapBillToViewHandelBarAgian(_listBillCurrent);
            }
        });

        ISS.EVENT.bindEvent('#columnBill_payment_' + bill[i].maHD, 'change', function () {
            var r = confirm("Bạn có muốn cập nhật ?");
            if (r == true) {
                var _payment = ISS.DOM.getVal('#'+this.id);
                var _id = ISS.DOM.getData('#' + this.id, 'id');

                ISS.BACKEND.request({
                    url: SERVER.contextPath + '/service/admin/updatePaymentBill/' + _id + '/' + _payment,
                    type: 'GET',
                    success: function (data) {
                        var responseInfo = data.responseObject;
                        if(responseInfo) {
                            var bill = [responseInfo];
                            updateCurrentlist(bill);
                            mapBillUpdateToViewHandelBar(bill);
                            alert('Cập nhật thành công !');
                        }
                        else {
                            alert('Cập nhật không thành công !');
                        }
                    }
                });
            }
            else {
                mapBillToViewHandelBarAgian(_listBillCurrent);
            }
        });
    }

    ISS.EVENT.bindEvent('#BillCommon_Delete', 'click', function () {
        ISS.DOM.removeClass('#boxTrackDeleteConfirm', 'hideBox');
    });

    ISS.EVENT.bindEvent('#buttonDeleteBillCommon_Agree', 'click', function () {
        ISS.DOM.addClass('#boxTrackDeleteConfirm', 'hideBox');
        deleteBillCommon();
    });

    ISS.EVENT.bindEvent('#buttonDeleteBillCommon_Cancel', 'click', function () {
        ISS.DOM.addClass('#boxTrackDeleteConfirm', 'hideBox');
    });

    ISS.EVENT.bindEvent('#buttonShowMessage_Hide', 'click', function () {
        ISS.DOM.addClass('#boxTrackShowMessage', 'hideBox');
    });
}

function deleteBillCommon(){
    var _listHoaDon = [];
    var _maHD = [];

    ISS.DOM.forEach('input[type="checkbox"]:checked', function(){
        _maHD.push(ISS.DOM.getVal(this));
    });

    if(_maHD.length > 0) {
        for(var i = 0; i < _maHD.length; i++) {
            var _bill = {};
            _bill.maHD = _maHD[i];
            _listHoaDon.push(_bill);
        }
        _listBillDelete = _listHoaDon;

        ISS.BACKEND.request({
            url: SERVER.contextPath + '/service/admin/deleteBill/',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            type: 'POST',
            dataType: 'json',
            data: JSON.stringify(_listHoaDon),
            success: function (data) {
                if(data.code == 0) {
                    deleteBillComplete();
//                    alert('Xoá thành công');
                    ISS.DOM.removeClass('#boxTrackShowMessage', 'hideBox');
                }
            }
        });
    }
    else {
        alert('Bạn chưa chọn hoá đơn');
    }
}

function updateCurrentlist(bill) {
    for(var i = 0; i < _listBillCurrent.length; i++) {
        if(_listBillCurrent[i].maHD == bill[0].maHD) {
            _listBillCurrent[i] = bill[0];
        }
    }
}

function deleteBillComplete() {
    var _list = [];
    for(var i = 0; i < _listBillCurrent.length; i++) {
        var count = 0;
        for(var j = 0; j < _listBillDelete.length; j++) {
            if(_listBillDelete[j].maHD != _listBillCurrent[i].maHD) {
                count += 1;
                if(count == _listBillDelete.length) {
                    _list.push(_listBillCurrent[i]);
                }
            }
        }
    }

    mapBillToViewHandelBarAgian(_list);
}

function mapBillUpdateToViewHandelBar(bill) {
    generaDataBill(bill);
    var tem = ISS.STRING_UTIL.format(ISS.TEMPLATE.handleBar.renderByString(TEMPLATE.BillCommon.billUpdate, bill[0]), {
        optionStatus: bill[0].optionStatus,
        optionPayment: bill[0].optionPayment
    });
    delete bill[0].optionStatus;
    delete bill[0].optionPayment;
    delete bill[0].showStatus;
    delete bill[0].showPayment;
    delete bill[0].showTick;
    ISS.DOM.html('#showData_' + bill[0].maHD, tem);

    bindEventUpdateBill(bill[0]);
}

function bindEventUpdateBill (bill) {
    ISS.EVENT.bindEvent('#columnBill_status_' + bill.maHD, 'change', function () {
        var r = confirm("Bạn có muốn cập nhật ?");
        if (r == true) {
            var _status = ISS.DOM.getVal('#'+this.id);
            var _id = ISS.DOM.getData('#' + this.id, 'id');

            ISS.BACKEND.request({
                url: SERVER.contextPath + '/service/admin/updateStatusBill/' + _id + '/' + _status,
                type: 'POST',
                success: function (data) {
                    var responseInfo = data.responseObject;
                    if(responseInfo) {
                        var bill = [responseInfo];
                        updateCurrentlist(bill);
                        mapBillUpdateToViewHandelBar(bill);
                        alert('Cập nhật thành công !');
                    }
                    else {
                        alert('Cập nhật không hợp lệ !');
                    }
                }
            });
        }
        else {
            mapBillToViewHandelBarAgian(_listBillCurrent);
        }
    });

    ISS.EVENT.bindEvent('#columnBill_payment_' + bill.maHD, 'change', function () {
        var r = confirm("Bạn có muốn cập nhật ?");
        if (r == true) {
            var _payment = ISS.DOM.getVal('#'+this.id);
            var _id = ISS.DOM.getData('#' + this.id, 'id');

            ISS.BACKEND.request({
                url: SERVER.contextPath + '/service/admin/updatePaymentBill/' + _id + '/' + _payment,
                type: 'GET',
                success: function (data) {
                    var responseInfo = data.responseObject;
                    if(responseInfo) {
                        var bill = [responseInfo];
                        updateCurrentlist(bill);
                        mapBillUpdateToViewHandelBar(bill);
                        alert('Cập nhật thành công !');
                    }
                    else {
                        alert('Cập nhật không thành công !');
                    }
                }
            });
        }
        else {
            mapBillToViewHandelBarAgian(_listBillCurrent);
        }
    });
}

function generaDataBillAgain(bill) {
    for(var i = 0; i < bill.length; i++) {
        switch (bill[i].thanhToan) {
            case 0 :
                bill[i].optionPayment = ISS.STRING_UTIL.format(TEMPLATE.BillCommon.comboBoxPayment0);
                bill[i].showPayment = true;
                break;
            case 1:
                bill[i].optionPayment = ISS.STRING_UTIL.format(TEMPLATE.BillCommon.comboBoxPayment1);
                bill[i].showPayment = false;
                break;
        }

        switch (bill[i].trangThai) {
            case 0 :
                bill[i].optionStatus = ISS.STRING_UTIL.format(TEMPLATE.BillCommon.comboBoxStatus0);
                bill[i].showStatus = true;
                bill[i].showTick = false;
                break;
            case 1:
                bill[i].optionStatus = ISS.STRING_UTIL.format(TEMPLATE.BillCommon.comboBoxStatus1);
                bill[i].showStatus = true;
                bill[i].showTick = false;
                break;
            case 2 :
                bill[i].optionStatus = ISS.STRING_UTIL.format(TEMPLATE.BillCommon.comboBoxStatus2);
                bill[i].showStatus = false;
                bill[i].showTick = false;
                break;
            case 3:
                bill[i].optionStatus = ISS.STRING_UTIL.format(TEMPLATE.BillCommon.comboBoxStatus3);
                bill[i].showStatus = false;
                bill[i].showPayment = false;
                bill[i].showTick = true;
                break;
        }
    }
}

function generaDataBill(bill) {
    for(var i = 0; i < bill.length; i++) {
        bill[i].ngayLapHD = bill[i].ngayLapHD ? ISS.DATE.getFullDate(new Date(bill[i].ngayLapHD)) : '';
        bill[i].ngayGiao = bill[i].ngayGiao ? ISS.DATE.getFullDate(new Date(bill[i].ngayGiao)) : '';
        bill[i].ngayNhan = bill[i].ngayNhan ? ISS.DATE.getFullDate(new Date(bill[i].ngayNhan)) : '';
        bill[i].tongTien = ISS.STRING_UTIL.formatNumeral(bill[i].tongTien, '0,0');

        switch (bill[i].thanhToan) {
            case 0 :
                bill[i].optionPayment = ISS.STRING_UTIL.format(TEMPLATE.BillCommon.comboBoxPayment0);
                bill[i].showPayment = true;
                break;
            case 1:
                bill[i].optionPayment = ISS.STRING_UTIL.format(TEMPLATE.BillCommon.comboBoxPayment1);
                bill[i].showPayment = false;
                break;
        }

        switch (bill[i].trangThai) {
            case 0 :
                bill[i].optionStatus = ISS.STRING_UTIL.format(TEMPLATE.BillCommon.comboBoxStatus0);
                bill[i].showStatus = true;
                bill[i].showTick = false;
                break;
            case 1:
                bill[i].optionStatus = ISS.STRING_UTIL.format(TEMPLATE.BillCommon.comboBoxStatus1);
                bill[i].showStatus = true;
                bill[i].showTick = false;
                break;
            case 2 :
                bill[i].optionStatus = ISS.STRING_UTIL.format(TEMPLATE.BillCommon.comboBoxStatus2);
                bill[i].showStatus = false;
                bill[i].showTick = false;
                break;
            case 3:
                bill[i].optionStatus = ISS.STRING_UTIL.format(TEMPLATE.BillCommon.comboBoxStatus3);
                bill[i].showStatus = false;
                bill[i].showPayment = false;
                bill[i].showTick = true;
                break;
        }
    }
}

/*function mapBillToView(bill) {
    if(bill.length != 0){
        var rows = bill.length;
        var columns = 1;
        var str = '';
        str += '<table id="BillTable" class="tablesorter tableBillCommonWidth align-center hoverBillTable">';
        str += '<thead>';
        str += '   <tr>';
        str += '       <th class="columnBillSTT">STT</th>';
        str += '       <th class="columnBillStick">Tick</th>';
        str += '       <th class="columnBillCode">Mã HĐ</th>';
        str += '       <th class="columnBillBuyer">Người mua</th>';
        str += '       <th class="columnBillRecipient">Người nhận (NN)</th>';
        str += '       <th class="columnBillPhone">Số ĐT (NN)</th>';
        str += '       <th class="columnBillAddress">Địa chỉ (NN)</th>';
        str += '       <th class="columnBillDate">Ngày lập</th>';
        str += '       <th class="columnBillDate">Ngày đặt</th>';
        str += '       <th class="columnBillDate">Ngày giao</th>';
        str += '       <th class="columnBillFinish">Hoàn tất<input id="BillCommon_StatusID" type="hidden"/></th>';
        str += '       <th class="columnBillNote">Ghi chú</th>';
        str += '       <th class="columnBillTotalCash">Tổng tiền (VND)</th>';
        str += '   </tr>';
        str += '</thead>';
        str += '<tbody>';
        for(var i = 0; i < rows; i++){
            if (i%2==0){
                str += '<tr onmouseover="set_hover(this);" onmouseout="remove_hover(this)" id="showData" class="column-Light tableTransparent">';
            }else{
                str += '<tr onmouseover="set_hover(this);" onmouseout="remove_hover(this)" id="showData" class="column-Light tableTransparent">';
            }

            if (bill[i].thanhToan==1){
                var result = 'Hoàn Tất';
            }else{
                result = 'Chưa hoàn tất';
            }

            for (var j = 0; j < columns; j++){
                str += '<td class="columnBillSTT tableBillPadding">' + (i+1) + '</td>';
                str += '<td class="columnBillStick tableBillPadding"><input onclick="highlight_row(this)" id="' + bill[i].maHD + '" type="checkbox" value="' + bill[i].maHD + '"/></td>';
                str += '<td class="columnBillCode tableBillPadding">' + bill[i].maHD + '</td>';
                str += '<td class="columnBillBuyer tableBillPadding" id="' + bill[i].thongTinThanhVien.maTV + '">' + bill[i].thongTinThanhVien.ho + ' ' +
                    bill[i].thongTinThanhVien.ten + '</td>';
                str += '<td class="columnBillRecipient tableBillPadding">' + bill[i].hoTenNN + '</td>';
                str += '<td class="columnBillPhone tableBillPadding">' + bill[i].soDTNN + '</td>';
                str += '<td class="columnBillAddress tableBillPadding" title="' + bill[i].diaChiNN + '">' + bill[i].diaChiNN.trunc(23,true) + '</td>';
                str += '<td class="columnBillDate tableBillPadding">' + ISS.DATE.getFullDate(new Date(bill[i].ngayLapHD)) + '</td>';
                str += '<td class="columnBillDate tableBillPadding">' + ISS.DATE.getFullDate(new Date(bill[i].ngayDat)) + '</td>';
                str += '<td class="columnBillDate tableBillPadding">' + ISS.DATE.getFullDate(new Date(bill[i].ngayGiao)) + '</td>';
                str += '<td class="columnBillFinish tableBillPadding">' + result + '</td>';
                str += '<td class="columnBillNote tableBillPadding" title="' + bill[i].ghiChu + '">' + bill[i].ghiChu.trunc(23,true) + '</td>';
                str += '<td class="columnBillTotalCash tableBillPadding">' + formatCurency(bill[i].tongTien, "VND") + '</td>';
            }
            str += '</tr>';
        }
        str +=   '</tbody>';
        str += '</table>';
    }else{
        str += '\nKhông có dữ liệu';
    }
    ISS.DOM.html('#BillCommon_All', str);
}*/

/*function mapBillSearchToView(bill) {
    var rows = bill.length;
    var columns = 1;
    var str = '';
    str += '<table id="BillTable" class="tablesorter tableBillCommonWidth align-center hoverBillTable">';
    str += '<thead>';
    str += '   <tr>';
    str += '       <th class="columnBillSTT">STT</th>';
    str += '       <th class="columnBillStick">Tick</th>';
    str += '       <th class="columnBillCode">Mã HĐ</th>';
    str += '       <th class="columnBillBuyer">Người mua</th>';
    str += '       <th class="columnBillRecipient">Người nhận (NN)</th>';
    str += '       <th class="columnBillPhone">Số ĐT (NN)</th>';
    str += '       <th class="columnBillAddress">Địa chỉ (NN)</th>';
    str += '       <th class="columnBillDate">Ngày lập</th>';
    str += '       <th class="columnBillDate">Ngày đặt</th>';
    str += '       <th class="columnBillDate">Ngày giao</th>';
    str += '       <th class="columnBillFinish">Hoàn tất<input id="BillCommon_StatusID" type="hidden"/></th>';
    str += '       <th class="columnBillNote">Ghi chú</th>';
    str += '       <th class="columnBillTotalCash">Tổng tiền (VND)</th>';
    str += '   </tr>';
    str += '</thead>';
    str += '<tbody>';
    for(var i = 0; i < rows; i++){
        if (i%2==0){
            str += '<tr onmouseover="set_hover(this);" onmouseout="remove_hover(this)" id="showData" class="column-Light tableTransparent">';
        }else{
            str += '<tr onmouseover="set_hover(this);" onmouseout="remove_hover(this)" id="showData" class="column-Light tableTransparent">';
        }

        if (bill[i].thanhToan==1){
            var result = 'Hoàn Tất';
        }else{
            result = 'Chưa hoàn tất';
        }

        for (var j = 0; j < columns; j++){
            str += '<td class="columnBillSTT tableBillPadding">' + (i+1) + '</td>';
            str += '<td class="columnBillStick tableBillPadding"><input onclick="highlight_row(this)" id="' + bill[i].maHD + '" type="checkbox" value="' + bill[i].maHD + '"/></td>';
            str += '<td class="columnBillCode tableBillPadding">' + bill[i].maHD + '</td>';
            str += '<td class="columnBillBuyer tableBillPadding" id="' + bill[i].thongTinThanhVien.maTV + '">' + bill[i].thongTinThanhVien.ho + ' ' +
                bill[i].thongTinThanhVien.ten + '</td>';
            str += '<td class="columnBillRecipient tableBillPadding">' + bill[i].hoTenNN + '</td>';
            str += '<td class="columnBillPhone tableBillPadding">' + bill[i].soDTNN + '</td>';
            str += '<td class="columnBillAddress tableBillPadding">' + bill[i].diaChiNN + '</td>';
            str += '<td class="columnBillDate tableBillPadding">' + ISS.DATE.getFullDate(new Date(bill[i].ngayLapHD)) + '</td>';
            str += '<td class="columnBillDate tableBillPadding">' + ISS.DATE.getFullDate(new Date(bill[i].ngayDat)) + '</td>';
            str += '<td class="columnBillDate tableBillPadding">' + ISS.DATE.getFullDate(new Date(bill[i].ngayGiao)) + '</td>';
            str += '<td class="columnBillFinish tableBillPadding">' + result + '</td>';
            str += '<td class="columnBillNote tableBillPadding">' + bill[i].ghiChu + '</td>';
            str += '<td class="columnBillTotalCash tableBillPadding">' + bill[i].tongTien + '</td>';
        }
        str += '</tr>';
    }
    str +=   '</tbody>';
    str += '</table>';
    ISS.DOM.html('#BillSearch_All', str);
}*/

function mapBillDetailToView(bill) {
    var rows = bill.length;
    var columns = 1;
    var str = '';
    str += '<table class="scroll align-center">';
    str += '<thead>';
    str += '   <tr>';
    str += '       <th class="columnSTT">STT</th>';
    str += '       <th class="columnStick">Tick</th>';
    str += '       <th class="columnRule">Mã CTHĐ</th>';
    str += '       <th class="columnRule">Mã HĐ</th>';
    str += '       <th class="columnRule">Tên sản phẩm</th>';
    str += '       <th class="columnRule">Số lượng</th>';
    str += '       <th class="columnRule">Tổng giá (SL x ĐG)</th>';
    str += '   </tr>';
    str += '</thead>';
    str += '<tbody>';
    for(var i = 0; i < rows; i++){
        if (i%2==0){
            str += '<tr class="column-Dark">';
        }else{
            str += '<tr class="column-Light">';
        }

        for (var j = 0; j < columns; j++){
            str += '<td class="columnSTT">' + i + '</td>';
            str += '<td class="columnStick"><input id="' + bill[i].maHD + '" type="checkbox" value="' + bill[i].maHD + '"/></td>';
            str += '<td class="columnRule">' + bill[i].maHD + '</td>';
            str += '<td class="columnRule">' + bill[i].hoaDon.maHD + '</td>';
            str += '<td class="columnRule">' + bill[i].chiTietSanPham.maCTSP + ' - ' + bill[i].chiTietSanPham.sanPham.tenSP + '</td>';
            str += '<td class="columnRule">' + bill[i].soLuong + '</td>';
            str += '<td class="columnRule">' + bill[i].tongGia + '</td>';
        }
        str += '</tr>';
    }
    str +=   '</tbody>';
    str += '</table>';
    ISS.DOM.html('#BillDetailCommon_All', str);
}

function mapMemberBillToView(member) {
    var html = '<option selected="selected" value="non_value">Mời chọn...</option>';
    for(var i=0; i<member.length; i++) {
        html += '<option value="' + member[i].maTV + '">' + member[i].maTV + ' - ' + member[i].ho + ' ' + member[i].ten + '</option>';
    }
    ISS.DOM.html('#BillCommon_Member', html);
}

function mapBillCodeToView(billcode) {
    var html = '<option selected="selected" value="non_value">Mời chọn...</option>';
    for(var i=0; i<billcode.length; i++) {
        html += '<option value="' + billcode[i].maHD + '">' + billcode[i].maHD + ' - ' + billcode[i].thongTinThanhVien.maTV + '</option>';
    }
    ISS.DOM.html('#BillDetail_Option', html);
}

function mapProductDetailCodeToView(product) {
    var rows = product.length;
    var columns = 1;
    var str = '';
    str += '<table class="scroll align-center">';
    str += '<thead>';
    str += '   <tr>';
    str += '       <th class="columnSTT">STT</th>';
    str += '       <th class="columnStick">Tick</th>';
    str += '       <th class="columnList">Danh mục</th>';
    str += '       <th class="columnTitle-summary">Tên</th>';
    str += '       <th class="columnColor">Màu</th>';
    str += '       <th class="columnSize">Size</th>';
    str += '       <th class="columnSexual">ĐT</th>';
    str += '       <th class="columnPicture">Hình ảnh</th>';
    str += '       <th class="columnPatern">Hoạt tiết</th>';
    str += '       <th class="columnQuantity-Product-Detail-summary">SL hiện có</th>';
    str += '       <th class="columnQuantity-Product-Detail-summary">SL bán</th>';
    str += '       <th class="columnPrice-summary-product-detail">Đơn giá (VND)</th>';
    str += '       <th class="columnPrice-summary-product-detail">Tổng giá (SL*ĐG)</th>';
    str += '   </tr>';
    str += '</thead>';
    str += '<tbody>';
    for(var i = 0; i < rows; i++){
        if (i%2==0)
        {
            str += '<tr class="column-Dark">'
        }
        else
        {
            str += '<tr class="column-Light">'
        }
        for (var j = 0; j < columns; j++){
            str += '<td class="columnSTT">' + (i+1) + '</td>';
            str += '<td class="columnStick"><input id="' + product[i].maCTSP + '" type="checkbox" value="' + product[i].maCTSP + '"/></td>';
            str += '<td class="columnList" id="' + product[i].sanPham.loaiDanhMucSanPham.maLoaiDMSP + '">' + product[i].sanPham.loaiDanhMucSanPham.tenLoaiDMSP + '</td>';
            str += '<td class="columnTitle-summary">' + product[i].sanPham.tenSP + '</td>';
            str += '<td class="columnColor" id="' + product[i].mauSac.maMau + '">' + product[i].mauSac.tenMau + '</td>';
            str += '<td class="columnSize" id="' + product[i].kichThuoc.maSize + '">' + product[i].kichThuoc.tenSize + '</td>';
            str += '<td class="columnSexual">' + product[i].sanPham.doiTuong + '</td>';
            str += '<td class="columnPicture">Picture ' +  i + '.jpg</td>';
            str += '<td class="columnPatern" id="' + product[i].hoaTiet.maHoaTiet + '">' +  product[i].hoaTiet.tenHoaTiet + '</td>';
            str += '<td class="columnQuantity-Product-Detail-summary">' +   product[i].soLuong + '</td>';
            str += '<td class="columnQuantity-Product-Detail-summary"><input size="1" id="BillDetail_QuantitySell_' + product[i].maCTSP + '" type="text"/></td>';
            str += '<td class="columnPrice-summary-product-detail">'+ product[i].giaSP +'</td>';
            str += '<td class="columnPrice-summary-product-detail"><input size="1" id="BillDetail_TotalPrice_' + product[i].maCTSP + '" type="text"/></td>';
        }
        str += '</tr>';
    }
    str +=   '</tbody>';
    str += '</table>';
    ISS.DOM.html('#BillDetail_Product', str);
}

function clearValidateInfo_Add() {
    ISS.DOM.removeClass('#BillCommon_Code', 'error-input-not-null');
    ISS.DOM.removeClass('#BillCommon_Member', 'error-input-not-null');
    ISS.DOM.removeClass('#BillCommon_Receiver', 'error-input-not-null');
    ISS.DOM.removeClass('#BillCommon_ReceiverAddress', 'error-input-not-null');
    ISS.DOM.removeClass('#BillCommon_ReceiverPhone', 'error-input-not-null');
    ISS.DOM.removeClass('#BillCommon_DateCreate', 'error-input-not-null');
    ISS.DOM.removeClass('#BillCommon_DateBegin', 'error-input-not-null');
    ISS.DOM.removeClass('#BillCommon_DateEnd', 'error-input-not-null');
    ISS.DOM.removeClass('#BillCommon_Status', 'error-input-not-null');
    ISS.DOM.removeClass('#BillCommon_Finish', 'error-input-not-null');
    ISS.DOM.removeClass('#BillCommon_Total', 'error-input-not-null');
}

function hideBoxConfirm() {
    ISS.DOM.addClass('#boxTrackConfirm', 'hideBox');
}